<?php

class Search_MobileController extends Ac_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
        $this->_helper->layout->setLayout('layout-mobile2');
    }

    public function indexAction()
    {
    	//$this->_helper->layout->setLayout('layout-mobile');
    	//$this->view->main_content = "mobile/result.phtml";
		$this->view->module_content = "search";
		//echo "SEARCH";exit();
        $this->_forward('regular');
    }

    public function regularAction()
    {
    	//echo "SEARCH";exit();
        //echo '<pre>';print_r($_GET);exit;

        //var_dump($this->_title);exit;
        //Make Browse tab ORANGE..
        if(strpos($_SERVER["REQUEST_URI"], '/c/')===false)
        	$this->view->browse_check=false;
        else
        	$this->view->browse_check=true;
        
        $get = $_GET;
        
        if(!empty($get['key_search_tools']['keywords']))
		{
			$get['keyword'] = $get['key_search_tools']['keywords'];
			
		}
		
		if(!empty($get['key_search_tools']['small_category_list']))
        {
			$get['small_category_list'] = $get['key_search_tools']['small_category_list'];
		}	
        	
        if(!empty($get['key_search_tools']['district']))
        {
			$get['district'] = $get['key_search_tools']['district'];
		}
        
        if(empty($get['keyword'])) {
            $get['keyword'] = '';
        } else {
            /*
            $get['keyword'] = str_replace(' ', '+', $get['keyword']).' '.$get['keyword'];
            $get['keyword_boost'] = '"'.str_replace(' ', ' ', $_GET['keyword']).'"^3';
             *
             */
        }

        if (!empty($_GET['keyword']) && Ac_Util::checkBadWord($_GET['keyword'])) {
            $this->view->disclamer = 1;
        }
        
        $category = '';
        //print_r($_GET['category_list']);exit;
        $get['category_list'] = empty($get['small_category_list']) ? '' :$get['small_category_list'];
        
        if (Zend_Registry::isRegistered('category_list_id')) {
            $id = Zend_Registry::get('category_list_id');            
            $cat = Model_Category::find($id);
            $this->view->category = $cat;
            if (empty($cat->customization)) {
                $get['small_category_list'] = $id;
            }
            else {
                $get['small_category_list'] = $cat->customization;
            }            
            $get['category_list'] = $cat->customization;
            $main_cat = $cat->_id;
            $category = ' +category:'.(string) $id;
            $_GET['small_category_list'] = $get['small_category_list'];
        }
        
        //no categories selected but category was forwarded from browse
        if(empty($get['key_search_tools']['small_category_list']) && empty($get['small_category_list']) && !empty($get['hidden_small_cat']) )
		{
			$get['small_category_list'] = $get['hidden_small_cat'];
			$category = ' +category:'. $get['hidden_small_cat'];
		}
        
        $form2 = new Search_Form_RegularMobileForm();
        $this->view->form2 = $form2->setAction($this->view->geturl('regular', 'search'))->setMethod('get');
        
        $solr = Ac_Search::getClient();

        $get['sort'] = !empty($get['sort']) ? $get['sort'] : '';
        $page      = !empty($get['page']) ? $get['page'] : 1;
        $per_page  = 10;
        $classname = Model_Search::getListingInstance($get['category_list']);
        //print_r($_GET['category_list']);exit;
        //echo $get['keyword'];exit;
        $listing   = new $classname;
        $listing->processRefineSearchForm($get, $page, $per_page, $query, $fields, $additionalParameters);
        
        if (!empty($listing)) {
            $list = $listing::one();
            //echo $list->category[0]->path[0]."line 74..........";
            $main_cat = Model_Category::find($list->category[0]->path[0]);
            Zend_Registry::set('main_category', $main_cat);
        }
        
        $this->view->sort = $get['sort'];
        if (empty($additionalParameters['fq'])) {
            $additionalParameters['fq'] = '';
        }
        if (!empty($category)) {
            $additionalParameters['fq'] .= $category;
        }
        //Only show PUBLISHED Ads
        if (empty($additionalParameters['fq'])) {
            $additionalParameters['fq'] .= ' +status:1 +type_obj_s:Model_Listing ';
        }
        else {
            $additionalParameters['fq'] .= ' +status:1 ';
        }
        
        if(!empty($get['key_search_tools-price']) && empty($get['key_search_tools-price-1']))
        {
			$additionalParameters['fq'] = preg_replace('/[0-9]+[\sTO\s]+[0-9]+/',$get['key_search_tools-price'].' TO *',$additionalParameters['fq']);
		}
        
        
        
        $form = $listing->getRefineSearchForm(array('initialize' => false));
        
        //$form = new Search_Form_RegularMobileForm();
                
        $form->populate($_GET);
        $form->init();

        //load bookmark
        $list = Model_Bookmark::getList();
        $bookmark = array();
        if (!empty($list)) {
            foreach($list as $bmk) {
                $bookmark[] = (string) $bmk->listing->_id;
            }
        }
        $this->view->bookmark = $bookmark;

        if (APPLICATION_ENV != 'production') {
            echo '<pre style="clear:both">';
            var_dump($_GET);
            var_dump($page, $per_page, $query);
            var_dump($additionalParameters);
            echo '</pre>';
        }

        $start = ($page-1) * $per_page;
        $list = $solr->search($query, $start, $per_page, $additionalParameters);

        $this->view->query = $query;

        $this->view->item_partial   = $listing->getSearchResultPartialName();
        $this->view->list           = $list->response->docs;
        $this->view->listing_number = $list->response->numFound;
        $this->view->page           = $page;
        $this->view->per_page       = $per_page;
        $this->view->form           = $form->setAction($this->view->geturl('regular', 'search'))->setMethod('get');

        $search = new Model_search();
        $search->url = $_SERVER["REQUEST_URI"];
        $search->get = $_GET;
        $search->user = !empty($this->loggedin_user) ? $this->loggedin_user->_id : '';
        $search->save();
        $this->view->search_id = $search->_id;
        $this->render('result');
    }

    public function getCounterAction()
    {
        if(empty($_GET['keyword'])) {
            $_GET['keyword'] = '';
        }
        
        $category = '';
        $_GET['category_list'] = '';
        if (Zend_Registry::isRegistered('category_list_id')) {
            $id = Zend_Registry::get('category_list_id');
            $cat = Model_Category::find($id);
            $_GET['small_category_list'] = $cat->customization;
            $category = ' +category:'.(string) $id;
        }

        $solr = Ac_Search::getClient();
        $_GET['sort'] = 'recent';

        //$query = '+type_obj:'.Model_Listing::TYPE.' +title:'.$keyword.' +description:'.$keyword. ' ' . $category;
        $classname = Model_Search::getListingInstance($_GET['small_category_list']);
        $listing   = new $classname;
        $get = $_GET;
        $listing->processRefineSearchForm($get, 1, 1, $query, $fields, $additionalParameters);

        //Only show PUBLISHED Ads
        $additionalParameters['fq'] .= ' +status:1';

        /*
        echo '<pre style="clear:both">';
        print_r($_GET);
        print_r($query);
        print_r($additionalParameters);
        echo '</pre>';
        */

        try {
            $list = $solr->search($query, 0, 0, $additionalParameters);
            echo (int) $list->response->numFound;
            exit;
        } catch (Exception $e) {
            if (APPLICATION_ENV != 'production') {
                echo $classname;
                print_r($additionalParameters);
                echo 'error';
            }
        }
        
        
    }

    public function getAttributeAction()
    {
        $class    = $_GET['c'];
        $function = $_GET['f'];

        //Class Cars
        if ($class == 'car' && $function == 'model') {
            $list = Model_Listing_Car::getModel($_GET['id']);
        }
        if ($class == 'car' && $function == 'postad') {
            $list = Model_Listing_Car::getModelPostAd($_GET['id']);
        }
        //Class Motorcycles
        if ($class == 'motorcycle' && $function == 'model') {
            $list = Model_Listing_Motorcycle::getModel($_GET['id']);
        }
        if ($class == 'motorcycle' && $function == 'postad') {
            $list = Model_Listing_Motorcycle::getModelPostAd($_GET['id']);
        }
        //Class Boats : Boat Type/Boat Category
        if ($class == 'boattype' && $function == 'model') {
            $list = Model_Listing_Boat::getBoatCategory($_GET['id']);
        }
        if ($class == 'boattype' && $function == 'postad') {
            $list = Model_Listing_Boat::getBoatCategoryPostAd($_GET['id']);
        }

        //Class Jobs
        if ($class == 'job' && $function == 'model') {
            $list = Model_Listing_Job::getJobFunctionPostAd($_GET['id']);
        }
        if ($class == 'job1' && $function == 'model') {
            $list = Model_Listing_Job::getJobFunction($_GET['id']);
        }
        //Class Location
        if ($class == 'area' && $function == 'district') {
            $list = Model_Location::getDistrict($_GET['id']);
        }
        //Class Location bis
        if ($class == 'area' && $function == 'district_bis') {
            $list = Model_Location::getDistrictSearch($_GET['id']);
        }
        //Class Location Post Ad
        if ($class == 'area' && $function == 'district_postad') {
            $list = Model_Location::getDistrictPostAd($_GET['id']);
        }
        //Class Boats : Make
        if ($class == 'boats' && $function == 'model')
        {
            $list = Model_Listing_Boat::getBoats($_GET['term']);
            Zend_Controller_Action_HelperBroker::addHelper(
                new ZendX_JQuery_Controller_Action_Helper_AutoComplete()
            );
            $this->_helper->json($list);
        }        
        else
        {
            $this->_helper->json($list);
        }
        
    }
}
